import * as React from 'react';
import { createApp, config, APP_MODE} from 'ice';
import LocaleProvider from '@/components/LocaleProvider';
import { getLocale } from '@/utils/locale';
import {  Message } from '@alifd/next';
const locale = getLocale();
// console.log(APP_MODE)
const appConfig = {
  app: {
    rootId: 'ice-container',
    addProvider: ({ children }) => (
      <LocaleProvider locale={locale}>{children}</LocaleProvider>
    ),
  },
  router: {
    type: 'browser',
    fallback: <div>loading...</div>,
    modifyRoutes: (routes) => {
      console.log(routes);
      return routes;
    }
  },
  request: {
    baseURL: config.baseURL,
    timeout: 50000,
    // 拦截器
    interceptors: {
      request: {
        onConfig: (requestConfig) => {
          // 发送请求前：可以对 RequestConfig 做一些统一处理
          const tokenData = localStorage.getItem('token');
          if (tokenData) {
            requestConfig.headers = {
              Authorization: `Bearer ${tokenData}`,
              token: `123456 ${tokenData}`,
              ...requestConfig.headers,
            };
          } else {
            requestConfig.headers = {
              ...requestConfig.headers,
            };
          }
          const time = new Date().getTime();
          if (requestConfig.params) {
            requestConfig.params.timer = time;
          } else if (requestConfig.url && requestConfig.url.indexOf('?') === -1) {
            requestConfig.url += `?timer=${  time}`;
          } else {
            requestConfig.url += `&timer=${  time}`;
          }
          return requestConfig;
        },
        onError: (error) => {
          return Promise.reject(error);
        }
      },
      response: {
        onConfig: (res) => {
          if (Object.prototype.toString.call(res.data) === '[object Object]') {
            if (res.data.code === 0 || res.data.resCode === 200) {
              return res;
            }
          }
          // 获取验证码
          if (Object.prototype.toString.call(res.data) === '[object String]') {
            const result = res.data;
            return Promise.resolve(result);
          }
          const error = res.data || {};
          if (error.code === 501001) {
            localStorage.token = '';
            Message.error('token过期，请重新登陆');
            // history.push('/user/login');
          } else if (error.code === 501217) {
            return Promise.resolve(error);
          } else {
            error.msg = error.msg || '接口调用失败';
            Message.error(error.msg);
            return Promise.reject(error);
          }
          return res;
        },
        onError: (error) => {
          // 请求出错：服务端返回错误状态码
          const err = error || {};
          err.msg = error.msg || '接口调用失败';
          return Promise.reject(err);
        }
      }
    }
  }
};
createApp(appConfig);
